package com.tenton.kafka;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * @Author：TangDong
 * @Date：2022/3/29
 * @Description：
 */
@Slf4j
@Component
public class KafkaProducer {
    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;
    //自定义topic
    public static final String TOPIC_TEST = "topic_test";
    //自定义group
    public static final String TOPIC_GROUP1 = "topic_group1";
    public static final String TOPIC_GROUP2 = "topic_group2";
    
    public void send(Object obj){
        String jsonString = JSONObject.toJSONString(obj);
        log.info("准备发送消息为：{}" + jsonString);
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(TOPIC_TEST, obj);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable ex) {
                //发送失败的处理
                log.info(TOPIC_TEST + " - 生产者 发送消息失败：" + ex.getMessage());
            }
    
            @Override
            public void onSuccess(SendResult<String, Object> result) {
                //成功的处理
                log.info(TOPIC_TEST + " - 生产者 发送消息成功：" + result.toString());
            }
        });
    }
}
